package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.service.CommentHotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class CommentHotServiceImpl implements CommentHotService {


    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 处理热点评论
     *
     * @param apComment
     */
    @Async  // 异步执行
    public void hotCommentExecutor(ApComment apComment) {
        //根据评论id,查询文章id和所有属于這篇文章的精选评论
        List<ApComment> apComments = mongoTemplate.find(Query.query
                        (Criteria.where("entryId").is(apComment.getEntryId())
                                .and("flag").is((short) 1)
                        ).with(Sort.by(Sort.Direction.DESC, "likes"))
                , ApComment.class);
        if (apComments.size() < 5) {
            apComment.setFlag((short) 1);
            apComments.add(apComment);
            mongoTemplate.save(apComment);
            return;
        }
        if (apComments.size() == 5 && apComments.get(apComments.size() - 1).getLikes() < apComment.getLikes()) {
            apComments.get(apComments.size() - 1).setFlag((short)0);
            mongoTemplate.save( apComments.get(apComments.size() - 1));
            apComment.setFlag((short) 1);
            apComments.add(apComment);
            mongoTemplate.save(apComment);
        }
    }
}